package repository

import "gitee.com/llqhz/go-micro-user/user/domain/model"
import "github.com/jinzhu/gorm"

type IUserRepository interface {
	// InitTable 初始化数据表
	InitTable() error

	// FindUserByName 根据用户名称查找信息
	FindUserByName(name string) (*model.User, error)

	// FindUserById 根据Id查找用户
	FindUserById(id int64) (*model.User, error)

	// CreateUser 创建用户
	CreateUser(user *model.User) (id int64, err error)

	// DeleteUserById 删除用户
	DeleteUserById(id int64) error

	// UpdateUser 更新用户
	UpdateUser(user *model.User) error

	// FindAll 查找所有用户
	FindAll() ([]*model.User, error)
}

func NewUserRepository(db *gorm.DB) *UserRepository {
	return &UserRepository{db: db}
}

type UserRepository struct {
	db *gorm.DB
}

func (u *UserRepository) InitTable() error {
	return u.db.AutoMigrate(&model.User{}).Error
}

func (u *UserRepository) FindUserByName(name string) (*model.User, error) {
	user := &model.User{}
	return user, u.db.Where("user_name = ?", name).Find(user).Error
}

func (u *UserRepository) FindUserById(id int64) (*model.User, error) {
	user := &model.User{}
	return user, u.db.Where("id = ?", id).Find(user).Error
}

func (u *UserRepository) CreateUser(user *model.User) (id int64, err error) {
	return user.ID, u.db.Create(user).Error
}

func (u *UserRepository) DeleteUserById(id int64) error {
	return u.db.Where("id = ?", id).Delete(&model.User{}).Error
}

// UpdateUser
// @Description: 更新用户纪录
// @receiver u
// @param user *model.User
// @return error
func (u *UserRepository) UpdateUser(user *model.User) error {
	return u.db.Model(user).Update(&user).Error
}

func (u *UserRepository) FindAll() ([]*model.User, error) {
	users := []*model.User{}
	return users, u.db.Find(users).Error
}
